/*
网络各种接收发送方式
JSON_string转map
*/

package ucommon

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"strings"
)

//FIXME:发送GET请求，返回完整BODY

func Get(url *string) string {
	res, err := http.Get(*url)
	if err != nil {
		return ""
	}
	if res.StatusCode != 200 {
		fmt.Println("Http GET status code:", res.StatusCode)
		return ""
	}

	defer res.Body.Close()

	robots, err1 := io.ReadAll(res.Body)
	if err1 != nil {
		return ""
	}
	return string(robots)
}

//FIXME:发送POST请求，返回完整BODY
/*
Post("http://xxxx","application/json;charset=utf-8",[]byte("{'aaa':'bbb'}"))
*/
func Post(url, contentType *string, body []byte) (string, error) {
	res, err := http.Post(*url, *contentType, strings.NewReader(string(body)))
	if err != nil {
		return "", err
	}
	if res.StatusCode != 200 {
		fmt.Println("Http POST status code:", res.StatusCode)
		return "", err
	}
	defer res.Body.Close()
	content, err := io.ReadAll(res.Body)
	if err != nil {
		return "", err
	}
	return string(content), nil
}

/*
json,参考网址（https://www.jb51.net/article/209066.htm）
*/

// TODO:string转map
func JsonToMap(str *string) map[string]interface{} {
	var tempMap map[string]interface{}
	err := json.Unmarshal([]byte(*str), &tempMap)
	if err != nil {
		panic(err)
	}
	return tempMap
}

//TODO:map转string

func MapToJson(param *map[string]interface{}) string {
	dataType, _ := json.Marshal(*param)
	dataString := string(dataType)
	return dataString
}
